// video.js
const { videoAPI } = require('../../interface.js')

Page({
  data: {
    videoList: [],
    hasMore: true,
    loading: false,
    refreshing: false,
    currentPage: 1,
    pageSize: 20,
    followedList: []
  },

  onLoad() {
    // 页面加载时获取视频列表
    this.getVideoList()
    // 初始化关注列表
    this.initFollowedList()
  },

  onShow() {
    // 页面显示时刷新数据
    this.refreshVideoList()
  },

  // 获取视频列表
  async getVideoList(isRefresh = false) {
    if (this.data.loading) return
    
    this.setData({ loading: true })
    
    try {
      const page = isRefresh ? 1 : this.data.currentPage
      const res = await videoAPI.getVideoList(page, this.data.pageSize)
      
      if (res.code === 200) {
        const newVideoList = res.data.videos || []
        // 为每个视频添加关注状态
        const processedVideoList = this.processVideoListWithFollowStatus(newVideoList)
        
        this.setData({
          videoList: isRefresh ? processedVideoList : [...this.data.videoList, ...processedVideoList],
          currentPage: isRefresh ? 2 : this.data.currentPage + 1,
          hasMore: newVideoList.length === this.data.pageSize,
          loading: false,
          refreshing: false
        })
      } else {
        wx.showToast({
          title: res.msg || '获取视频列表失败',
          icon: 'none'
        })
        this.setData({ loading: false, refreshing: false })
      }
    } catch (error) {
      console.error('获取视频列表失败:', error)
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none'
      })
      this.setData({ loading: false, refreshing: false })
    }
  },

  // 下拉刷新
  async onPullDownRefresh() {
    this.setData({ refreshing: true })
    await this.getVideoList(true)
    wx.stopPullDownRefresh()
  },

  // 刷新视频列表
  refreshVideoList() {
    this.setData({
      currentPage: 1,
      videoList: [],
      hasMore: true
    })
    this.getVideoList(true)
  },

  // 跳转到详情页
  goToDetail(e) {
    const videoId = e.currentTarget.dataset.id
    // 官方文档: https://developers.weixin.qq.com/miniprogram/dev/api/route/wx.navigateTo.html
    wx.navigateTo({
      url: `/pages/video-detail/video-detail?id=${videoId}`
    })
  },



  // 跳转到上传页面
  goToUpload() {
    wx.navigateTo({
      url: '/pages/upload/upload'
    })
  },

  // 滚动到底部触发加载
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.getVideoList(false)
    }
  },

  // 自定义tabBar切换事件
  onTabChange(e) {
    const { index, path } = e.detail;
    // 可以在这里添加切换前的逻辑处理
    console.log('Tab切换:', index, path);
  },

  // 广告事件处理
  adLoad() {
    console.log('原生模板广告加载成功')
  },
  
  adError(err) {
    console.error('原生模板广告加载失败', err)
  },
  
  adClose() {
    console.log('原生模板广告关闭')
  },

  // 初始化关注列表
  initFollowedList() {
    const followedList = wx.getStorageSync('followedAuthors') || []
    this.setData({ followedList })
  },

  // 处理视频列表，添加关注状态
  // 格式化观看数为万为单位
  formatViewCount(count) {
    if (count >= 10000) {
      return (count / 10000).toFixed(1)
    }
    return (count / 10000).toFixed(1)
  },

  // 格式化分享数
  formatShareCount(count) {
    if (!count) return '0'
    if (count >= 10000) {
      return Math.floor(count / 10000) + '万'
    }
    return count.toString()
  },

  processVideoListWithFollowStatus(videoList) {
    const followedList = this.data.followedList || []
    return videoList.map(video => ({
      ...video,
      isFollowed: followedList.includes(video.author_nickname),
      formattedViewCount: this.formatViewCount(video.view_count),
      formattedShareCount: this.formatShareCount(video.share_count || Math.floor(Math.random() * 5000) + 100)
    }))
  },

  // 切换关注状态
  toggleFollow(e) {
    // 阻止事件冒泡，防止跳转到详情页
    if (e && e.stopPropagation) {
      e.stopPropagation()
    }
    
    if (!e || !e.currentTarget || !e.currentTarget.dataset) {
      console.error('Event object or dataset is missing')
      return
    }
    
    const { nickname, index } = e.currentTarget.dataset
    let followedList = [...(this.data.followedList || [])]
    let videoList = [...this.data.videoList]
    
    const isCurrentlyFollowed = followedList.includes(nickname)
    
    if (isCurrentlyFollowed) {
      // 取消关注
      followedList = followedList.filter(name => name !== nickname)
      videoList[index].isFollowed = false
      wx.showToast({
        title: '已取消关注',
        icon: 'success'
      })
    } else {
      // 添加关注
      followedList.push(nickname)
      videoList[index].isFollowed = true
      wx.showToast({
        title: '关注成功',
        icon: 'success'
      })
    }
    
    // 更新本地存储
    wx.setStorageSync('followedAuthors', followedList)
    
    // 更新页面数据
    this.setData({
      followedList,
      videoList
    })
  },

  // 选择本地视频
  chooseLocalVideo() {
    // 官方文档: https://developers.weixin.qq.com/miniprogram/dev/api/media/video/wx.chooseVideo.html
    wx.chooseVideo({
      sourceType: ['album'],
      maxDuration: 300, // 5分钟
      success: (res) => {
        // 官方文档: https://developers.weixin.qq.com/miniprogram/dev/api/ui/interaction/wx.showToast.html
        wx.showToast({
          title: '本地视频选择成功',
          icon: 'success'
        })
        // 这里可以上传视频到服务器
        console.log('选择的本地视频:', res.tempFilePath)
        this.uploadVideoToServer(res.tempFilePath)
      },
      fail: () => {
        // 官方文档: https://developers.weixin.qq.com/miniprogram/dev/api/ui/interaction/wx.showToast.html
        wx.showToast({
          title: '取消选择',
          icon: 'none'
        })
      }
    })
  },

  // 录制视频
  recordVideo() {
    // 官方文档: https://developers.weixin.qq.com/miniprogram/dev/api/media/video/wx.chooseVideo.html
    wx.chooseVideo({
      sourceType: ['camera'],
      maxDuration: 60, // 1分钟
      camera: 'back',
      success: (res) => {
        // 官方文档: https://developers.weixin.qq.com/miniprogram/dev/api/ui/interaction/wx.showToast.html
        wx.showToast({
          title: '视频录制成功',
          icon: 'success'
        })
        // 这里可以上传视频到服务器
        console.log('录制的视频:', res.tempFilePath)
        this.uploadVideoToServer(res.tempFilePath)
      },
      fail: () => {
        // 官方文档: https://developers.weixin.qq.com/miniprogram/dev/api/ui/interaction/wx.showToast.html
        wx.showToast({
          title: '取消录制',
          icon: 'none'
        })
      }
    })
  },

  // 上传视频到服务器
  uploadVideoToServer(filePath) {
    // 官方文档: https://developers.weixin.qq.com/miniprogram/dev/api/ui/interaction/wx.showLoading.html
    wx.showLoading({
      title: '上传中...'
    })
    
    // 模拟上传过程
    setTimeout(() => {
      // 官方文档: https://developers.weixin.qq.com/miniprogram/dev/api/ui/interaction/wx.hideLoading.html
      wx.hideLoading()
      // 官方文档: https://developers.weixin.qq.com/miniprogram/dev/api/ui/interaction/wx.showToast.html
      wx.showToast({
        title: '上传成功',
        icon: 'success'
      })
      // 这里可以调用实际的上传API
      // wx.uploadFile({
      //   url: 'your-upload-api-url',
      //   filePath: filePath,
      //   name: 'video',
      //   success: (res) => {
      //     console.log('上传成功:', res)
      //   }
      // })
    }, 2000)
  }
})